package com.liuzhilin.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuzhilin.service.MessageService;
import com.liuzhilin.util.Response;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@WebServlet("/emailAddUser")
public class EmailAddUser extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        Response.setCorsHeaders(response);
        PrintWriter out = response.getWriter();
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // 获取请求体中的 JSON 数据
            StringBuilder sb = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            String json = sb.toString();
            Map<String, String> data = objectMapper.readValue(json, Map.class);
            String currentUsername = data.get("currentUsername");
            String friendUsername = data.get("friendUsername");
            // 连接数据库并插入好友关系
            boolean addFriendSuccess = MessageService.addFriend(currentUsername,friendUsername);

            // 返回响应
            if (addFriendSuccess) {
                out.print("{\"success\": true, \"message\": \"添加好友成功\"}");
                response.setStatus(HttpServletResponse.SC_OK);
            } else {
                out.print("{\"success\": false, \"message\": \"已经是好友关系了\"}");
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\": false, \"message\": \"服务器内部错误\"}");
        }
    }

    @Override
    protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Response.setCorsHeaders(response);
        response.setStatus(HttpServletResponse.SC_OK);
    }
}
